/**
 * phi
 */

// 定数
var SCREEN_SIZE = 640;
var PLAYER_MODEL    = "model/player.mqo";
var ENEMY_MODEL     = "model/virus.mqo";

// おまじない
enchant();

window.onload = function() {
    var game = new Game(SCREEN_SIZE, SCREEN_SIZE);
    
    game.preload(PLAYER_MODEL, ENEMY_MODEL);
    
    game.onload = function() {
        var scene = game.rootScene;
        var scene3d = new Scene3D();
        
        // ライト
        var light = new DirectionalLight();
        light.color = [1.0, 1.0, 1.0];
        scene3d.setDirectionalLight(light);
        
        // カメラ
        var camera = new Camera3D();
        camera.y = 1;
        camera.z = 15;
        camera.centerY =-1;
        scene3d.setCamera(camera);
        
        // プレイヤー
        var player = new Sprite3D();
        player.set(game.assets[PLAYER_MODEL]);
        scene3d.addChild(player);
        
        scene.ontouchmove = function(e) {
            player.x = (e.x/SCREEN_SIZE)*4-2;
            player.y =-((e.y/SCREEN_SIZE)*4-2);
        };
        
        scene.onenter = function() {
            game.frame = 0;
        };
        
        scene.onenterframe = function() {
            if (game.frame % 10 == 0) {
                var enemy = new Sprite3D();
                enemy.set(game.assets[ENEMY_MODEL]);
                enemy.x = Math.random()*4-2;
                enemy.y = Math.random()*4-2;
                enemy.z = -100;
                enemy.onenterframe = function() {
                    this.z += 1;
                    
                    // 消去
                    if (this.z > 15) {
                        this.parentNode.removeChild(this);
                    }
                }
                scene3d.addChild(enemy);
            }
            
            // 衝突判定
            for (var i=0,len=scene3d.childNodes.length; i<len; ++i) {
                var elm = scene3d.childNodes[i];
                if (elm != player && player.intersect(elm) == true) {
                    var seconds = game.frame/game.fps;
                    var score = seconds.toFixed();
                    console.log(score, score + "秒耐えました");
                    game.end(score, score + "秒耐えました");
                }
            }
        };
        
    };
    
    game.start();
};
